package gui.workers;

import gui.extra.progress.StatusMessenger;
import gui.extra.table.SearchColumnName;
import gui.extra.table.VideoTable;
import gui.extra.table.VideoTableModel;
import lib.Actions;
import lib.logging.Logger;
import lib.model.VideoFile;
import lib.model.VideoType;
import settings.model.Settings;

import javax.swing.*;
import java.io.File;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: lodder
 * Date: 4/12/11
 * Time: 8:52 AM
 * To change this template use File | Settings | File Templates.
 */
public class RenameWorker extends SwingWorker<Void, String> {

    private VideoTable table;
    private Settings settings;

    public RenameWorker(VideoTable table, Settings settings) {
        this.table = table;
        this.settings = settings;
    }

    protected Void doInBackground() throws Exception {
        final VideoTableModel model = (VideoTableModel) table.getModel();
        int selectedCount = model.getSelectedCount(table.getColumnIdByName(SearchColumnName.SELECT));
        int progress = 0;
        int k = 0;
        for (int i = 0; i < model.getRowCount(); i++) {
            if ((Boolean) model.getValueAt(i, table.getColumnIdByName(SearchColumnName.SELECT))) {
                k++;
                if (k > 0) progress = 100 * k / selectedCount;
                if (progress == 0 && selectedCount > 1) progress = 1;
                setProgress(progress);
                final VideoFile videoFile = (VideoFile) model.getValueAt(i, table.getColumnIdByName(SearchColumnName.OBJECT));
                if (videoFile.getVideoType() == VideoType.EPISODE) {
                    Logger.instance.debug("Treat as EPISODE");
                    Actions.rename(settings.getEpisodeLibrarySettings(),
                        new File(videoFile.getPath(), videoFile.getFilename()),
                        videoFile);
                }else if (videoFile.getVideoType() == VideoType.MOVIE){
                    Logger.instance.debug("Treat as MOVIE");
                    Actions.rename(settings.getMovieLibrarySettings(),
                        new File(videoFile.getPath(), videoFile.getFilename()),
                        videoFile);
                }
                model.removeRow(i);
                i--;
            }
        }
        return null;
    }

    protected void process(List<String> data) {
        for (String s : data)
            StatusMessenger.instance.message("Bestand hernoemen: " + s);
    }
}
